package com.topsec.manager.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;


/**
 * @author zhaoys
 * @date 2017年6月15日 上午11:13:23
 */
public class HttpUtil {
    // 日志记录器
    private final static Logger log = LoggerFactory.getLogger(HttpUtil.class);
    final static String url = "http://10.52.184.161:5000/config/ip-monitor/add";
    final static String params = "[{'direction':'1','start_time':'2015-5-22 16:13:26','proto':16,'ip':'5.5.5.5-5.5.5.6-ip','tool':1,'finder_id':'8000','end_time':'2018-5-23 16:13:27','hcmdd':1,'user_id':1,'port':'5000', 'hccl':1, 'monitor_type':0,'version_id':69880}]";

    /**
     * 发送HttpPost请求
     *
     * @param strURL 服务地址
     * @param params json字符串,例如: "{ \"id\":\"12345\" }" ;其中属性名必须带双引号<br/>
     * @return 成功:返回json字符串<br/>
     */
    public static String httpPost(String strURL, String params) {
        String result = "";
        BufferedReader in = null;
        try {
            log.info("请求地址【" + strURL + "】,请求参数【" + params + "】,请求方式【Post】");
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setConnectTimeout(30 * 1000);    // 响应时间
            connection.setReadTimeout(30 * 1000);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(params);
            out.flush();
            out.close();
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = e.getMessage();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String httpGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            log.info("请求地址【" + urlNameString + "】,请求方式【Get】");
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            /* connection.setReadTimeout(5*1000);    // 响应时间
             connection.setConnectTimeout(10*1000);*/
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            result = e.getMessage();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }


    /**
     * 将文件转换成byte[]
     *
     * @param filePath
     * @return
     */
    public static byte[] getBytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer;
    }


    public static void main(String[] args) {
//        String url = "http://10.52.184.161:5000/config/ip-monitor/add";
//        String para = "[{\"direction\":\"1\",\"start_time\":\"2017-12-13 11:25:43\",\"proto\":\"8\",\"ip\":\"1.1.1.1-1.1.1.3-ip\",\"tool\":1,\"finder_id\":\"123\",\"hcmdd\":\"1\",\"end_time\":\"2017-12-16 11:25:44\",\"user_id\":\"1\",\"port\":\"12\",\"hccl\":\"1\",\"monitor_type\":\"0\",\"version_id\":69880}]";
//        String s = httpPost(url, para);
//        System.out.println(s);


    }
}
